package cn.itcast.bos.action;

import java.util.concurrent.TimeUnit;

import javax.jms.JMSException;
import javax.jms.MapMessage;
import javax.jms.Message;
import javax.jms.Session;
import javax.ws.rs.core.MediaType;

import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang3.RandomStringUtils;
import org.apache.cxf.jaxrs.client.WebClient;
import org.apache.struts2.ServletActionContext;
import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.Namespace;
import org.apache.struts2.convention.annotation.ParentPackage;
import org.apache.struts2.convention.annotation.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Scope;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.jms.core.JmsTemplate;
import org.springframework.jms.core.MessageCreator;
import org.springframework.stereotype.Controller;

import com.opensymphony.xwork2.ActionContext;

import cn.itcast.bos.domain.constant.Constants;
import cn.itcast.bos.utils.BaseAction;
import cn.itcast.bos.utils.MailUtils;
import cn.itcast.crm.domain.Customer;

@Controller
@Scope("prototype")
@Namespace("/")
@ParentPackage("json-default")
public class CustomerAction extends BaseAction<Customer> {

	@Autowired
	@Qualifier("jmsQueueTemplate")
	private JmsTemplate jmsTempalte;

	@Action(value = "customer_sendSms")
	public String sendSms() {
		// 生成随机验证码
		String randomCode = RandomStringUtils.randomNumeric(6);
		// 将验证码保存到session中
		ServletActionContext.getRequest().getSession().setAttribute(model.getTelephone(), randomCode);
		System.out.println("生成的短信验证码是" + randomCode);

		// 编辑短信内容
		final String msg = "尊敬的用户你好：短信验证码为" + randomCode;
		// 调用SmsBase发送验证码给客户

		jmsTempalte.send("bos_sms", new MessageCreator() {

			@Override
			public Message createMessage(Session session) throws JMSException {
				MapMessage mapMessage = session.createMapMessage();
				mapMessage.setString("telephone", model.getTelephone());
				mapMessage.setString("msg", msg);
				return mapMessage;
			}
		});
		return NONE;
	}

	// 属性注入验证码
	private String checkcode;

	public void setCheckcode(String checkcode) {
		this.checkcode = checkcode;
	}

	// 注入redisTemplate
	@Autowired
	private RedisTemplate<String, String> redisTemplate;

	// 注册用户
	@Action(value = "customer_regist", results = {
			@Result(name = "success", type = "redirect", location = "signup-success.html"),
			@Result(name = "input", type = "redirect", location = "signup.html") })
	public String registCustomer() {
		String checkcode1 = (String) ServletActionContext.getRequest().getSession().getAttribute(model.getTelephone());
		// 校验短信验证码
		if (StringUtils.isBlank(checkcode1) || !checkcode1.equals(checkcode)) {
			System.out.println("短信验证码错误");
			return INPUT;
		} else {
			// 短信验证码校验通过
			WebClient.create("http://localhost:9002/bos_management/services/customerService/customer")
					.type(MediaType.APPLICATION_JSON).post(model);
			System.out.println("注册成功");

			// 生成激活码
			String activeCode = RandomStringUtils.randomNumeric(16);
			// 把验证码保存到redis中
			redisTemplate.opsForValue().set(model.getTelephone(), activeCode, 1, TimeUnit.DAYS);

			String content = "尊敬的客户你好,请于24小时内激活</br><a href='" + MailUtils.activeUrl + "?telephone="
					+ model.getTelephone() + "&activeCode=" + activeCode + "'>速运邮箱激活地址</a>";

			MailUtils.sendMail("速运快递邮箱激活邮件", content, model.getEmail());
			return SUCCESS;
		}
	}

	// 属性注入激活码
	private String activeCode;

	public void setActiveCode(String activeCode) {
		this.activeCode = activeCode;
	}

	// 激活邮箱
	@Action(value = "customer_activeMail")
	public String activeMail() throws Exception {
		ServletActionContext.getResponse().setContentType("text/html;charset=utf-8");
		// 1.先获取redis中的激活码
		String redisActiveCode = redisTemplate.opsForValue().get(model.getTelephone());
		System.out.println(model.getTelephone());
		// 判断redis中的激活码是否和传过来的激活码一致
		if (activeCode.equals(redisActiveCode)) {
			// 激活码一致
			// 防止重复绑定
			// 调用webservice 改变已注册用户的类型为1
			// 根据电话调用crm查询客户的type
			Customer customer = WebClient
					.create("http://localhost:9002/bos_management/services/customerService"
							+ "/findCustomerByTelephone/" + model.getTelephone())
					.type(MediaType.APPLICATION_JSON).accept(MediaType.APPLICATION_JSON).get(Customer.class);
			if (customer.getType() == null || customer.getType() != -1) {
				// 没有绑定，进行绑定
				WebClient.create("http://localhost:9002/bos_management/services/customerService"
						+ "/updateCustomerType/" + model.getTelephone()).type(MediaType.APPLICATION_JSON).put(null);
				ServletActionContext.getResponse().getWriter().println("邮箱绑定成功");

			} else {
				// 已经绑定
				ServletActionContext.getResponse().getWriter().println("邮箱已激活");
			}
		} else {
			// redis中的激活码失效或者和传过来的激活码不一致
			// 页面输出激活码失效
			ServletActionContext.getResponse().getWriter().println("激活码已失效");
		}
		redisTemplate.delete(model.getTelephone());
		return NONE;
	}
	//登陆校验
	@Action(value = "customer_login", results = {
			@Result(name = "success", location = "index.html#/myhome", type = "redirect"),
			@Result(name = "login", location = "login.html", type = "redirect") })
	public String login() {
		Customer customer = WebClient.create(Constants.CRM_MANAGEMENT_URL+"/services/customerService/login/"+model.getTelephone()+"/"+model.getPassword()).accept(MediaType.APPLICATION_JSON).get(Customer.class);
		if(null == customer){
			return LOGIN;
		}
		ServletActionContext.getRequest().getSession().setAttribute("customer", customer);
		return SUCCESS;
	}
}
